import { getBrandPage } from "@/api/basicArchives/brand"; // 品牌
import {
  addGoods,
  batchRecommendGoods,
  batchUpGoodsStatus,
  delGoods,
  delGoodsSpec,
  getGoodsList,
  getRuleList,
  getUnitItemList,
  importGoodsList,
  setGoodsSpen,
  upGoods
} from "@/api/basicArchives/goods";
import { getLabelPage } from "@/api/basicArchives/labelmanag"; // 标签
import { getProductPage as getCategoryPgae } from "@/api/basicArchives/productcate"; // 商品类目
import { getStoreSimplePage } from "@/api/basicArchives/storeManagement"; // 门店
import { getSupplierPage } from "@/api/basicArchives/supplierManagement"; // 供应商
import { ImageViewer } from "@/components/common/ImageViewer";
import { addDialog } from "@/components/ReDialog";
import { useRouterNavigation } from "@/router/utils";
import { dealDataExcept, dealDataRide, dealTreeList } from "@/utils/common";
import { message } from "@/utils/message";
import { handleTree } from "@/utils/tree";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection, getKeyList } from "@pureadmin/utils";
import dayjs from "dayjs";
import { ElMessageBox } from "element-plus";
import { type Ref, computed, h, onMounted, reactive, ref, watch } from "vue";
import { SetBrandPrice } from "../form/components";
import editForm from "../form/index.vue";

const tabType = ref(1);
const treeLoading = ref(false);
const treeData = ref([]);

export function useUser(tableRef?: Ref, treeRef?: Ref, uploadRef?: Ref) {
  const { push } = useRouterNavigation();
  const selectData = ref({
    categoryList: [],
    supplierList: [],
    labelList: [],
    unitItemlList: [],
    ruleList: [],
    brandList: [],
    storeList: []
  });
  const form = reactive({
    categoryId: null,
    goodsCode: "",
    goodsName: "",
    goodsStatus: "",
    supplierId: "",
    preStockStatus: "",
    labelIdList: [],
    labelIds: "",
    pageNum: 1,
    pageSize: 20
  });
  const currentTreeData = reactive({
    id: null,
    menuName: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const switchStyle = {
    "--el-switch-on-color": "#6abe39",
    "--el-switch-off-color": "#e84749"
  };
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 50, 100, 200],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      type: "expand",
      slot: "expand",
      fixed: "left",
      width: "30px"
    },
    {
      label: "商品名称",
      prop: "goodsName",
      width: 200,
      align: "left",
      fixed: "left",
      showOverflowTooltip: true,
      cellRenderer: ({ row }) => (
        <div class="flex items-center mr-[-12px]">
          <ImageViewer src={row.imageJson} />
          <div
            class="ml-[5px] text-blue-500 cursor-pointer flex-1 text-cut"
            onClick={() => showGoodsDetail(row)}
          >
            {row.goodsName}
          </div>
        </div>
      )
    },
    {
      label: "商品编码",
      prop: "goodsCode",
      align: "left",
      showOverflowTooltip: true,
      width: 150
    },
    {
      label: "商品条码",
      prop: "menuName3",
      width: 120,
      slot: "barCode"
    },
    {
      label: "商品类目",
      prop: "categoryName",
      width: 120
    },
    {
      label: "商品标签",
      prop: "labelList",
      width: 160,
      showOverflowTooltip: true,
      cellRenderer: ({ row }) => row.labelList.map(i => i.labelName).join(",")
    },
    {
      label: "商品进价",
      prop: "menuName7",
      width: 120,
      cellRenderer: ({ row }) =>
        row.goodsSpecList && row.goodsSpecList.length == 1
          ? dealDataExcept(row.goodsSpecList[0].buyPrice)
          : ""
    },
    {
      label: "预备货",
      prop: "preStockStatus",
      minWidth: 120,
      cellRenderer: ({ row }) => (row.preStockStatus == 1 ? "是" : "否")
    },
    {
      label: "关联供应商",
      prop: "supplierName",
      showOverflowTooltip: true,
      minWidth: 120
    },
    {
      label: "状态",
      prop: "goodsStatus",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          v-model={scope.row.goodsStatus}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle}
          beforeChange={() => onChangeStatus(scope as any)}
        />
      )
    },
    {
      label: "为你推荐",
      prop: "recommendStatus",
      minWidth: 90,
      cellRenderer: scope => (
        <>
          {scope.row.goodsType == 1 ? (
            "--"
          ) : (
            <el-switch
              v-model={scope.row.recommendStatus}
              active-value={1}
              inactive-value={0}
              active-text="已推荐"
              inactive-text="不推荐"
              inline-prompt
              style={switchStyle}
              beforeChange={() => onChangeRecommend(scope as any)}
            />
          )}
        </>
      )
    },
    {
      label: "计量单位",
      prop: "unitItemName",
      showOverflowTooltip: true,
      minWidth: 120
    },
    {
      label: "起订量",
      prop: "orderMin",
      minWidth: 100
    },
    {
      label: "推荐指数",
      prop: "recommendIndex",
      width: 130,
      cellRenderer: ({ row }) => (
        <>
          <el-rate
            model-value={dealDataExcept(row.recommendIndex, 10) || 0}
            disabled
            size="small"
          />
        </>
      )
    },
    {
      label: "创建人",
      prop: "createUserName",
      minWidth: 100
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      minWidth: 140,
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "更新人",
      prop: "updateUserName",
      minWidth: 100
    },
    {
      label: "更新时间",
      prop: "gmtModified",
      minWidth: 140,
      formatter: ({ gmtModified }) =>
        dayjs(gmtModified).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "备注",
      prop: "des",
      showOverflowTooltip: true,
      minWidth: 120
    },
    {
      label: "操作",
      align: "left",
      fixed: "right",
      width: 212,
      slot: "operation"
    }
  ];

  const childColumns: TableColumnList = [
    {
      label: "规格名称",
      prop: "goodsName",
      width: 200,
      align: "left",
      fixed: "left",
      slot: "specName"
      // cellRenderer: scope => (
      //   <>
      //     <div class="flex items-center mr-[-12px]">
      //       <ImageViewer src={scope.row.specImageJson} />
      //       <div class="ml-[5px] cursor-pointer flex-1 overflow-hidden whitespace-normal">
      //         {scope.row.specName}
      //       </div>
      //     </div>
      //   </>
      // )
    },
    {
      label: "规格编码",
      prop: "specCode",
      align: "left",
      width: 150,
      slot: "specCode"
    },
    {
      label: "规格条码",
      prop: "barCode",
      width: 120,
      slot: "barCode"
      // cellRenderer: ({ row }) => (
      //   <>
      //     <el-tooltip
      //       class="box-item"
      //       effect="dark"
      //       content={`主条码:${row.barCode} <br /> 辅助条码: ${row.auxiliaryBraCodeList && row.auxiliaryBraCodeList.length > 0 ? row.auxiliaryBraCodeList.join(",") : ""}`}
      //       placement="top-start"
      //     >
      //       <div>{row.barCode}</div>
      //     </el-tooltip>
      //   </>
      // )
    },
    {
      label: "商品类目",
      prop: "categoryName",
      width: 120
    },
    {
      label: "商品标签",
      prop: "labelList",
      width: 160
    },
    {
      label: "商品进价",
      prop: "buyPrice",
      width: 120,
      cellRenderer: ({ row }) => dealDataExcept(row.buyPrice)
    },
    {
      label: "预备货",
      prop: "preStockStatus",
      minWidth: 120
    },
    {
      label: "关联供应商",
      prop: "supplierName",
      minWidth: 120
    },
    {
      label: "状态",
      prop: "goodsStatus",
      minWidth: 90
    },
    {
      label: "为你推荐",
      prop: "recommendStatus",
      minWidth: 90
    },
    {
      label: "计量单位",
      prop: "unitItemName",
      minWidth: 120
    },
    {
      label: "起订量",
      prop: "orderMin",
      minWidth: 100
    },
    {
      label: "推荐指数",
      prop: "recommendIndex",
      minWidth: 100
    },
    {
      label: "创建人",
      prop: "createUserName"
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      minWidth: 140
    },
    {
      label: "操作",
      fixed: "right",
      width: 212,
      align: "left",
      slot: "operations"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  function handleUpdate(row) {
    console.log(row);
  }

  // 查看商品详情
  const showGoodsDetail = row => {
    push({
      path: `/basicArchives/goods/detail`,
      query: { id: row.id }
    });
  };

  // 查看日志
  const showOptLog = () => {
    push("/basicArchives/goods/log");
  };

  const dealBrandList = propList => {
    // bizType	业务类型 1品牌 0门店
    let brandGoodsPrice = [];
    let storeGoodsPrice = [];
    let goodsSpecBrandRelList = propList || [];
    goodsSpecBrandRelList.forEach(v => {
      v.id = v.bizId;
      v.discountSalePrice = dealDataExcept(v.discountSalePrice);
      v.storeBuyPrice = dealDataExcept(v.storeBuyPrice);
      v.storeSalePrice = dealDataExcept(v.storeSalePrice);
      v.score = dealDataExcept(v.score);
      v.discountScore = dealDataExcept(v.discountScore);
      if (v.bizType == 1) {
        // 品牌
        v.brandName =
          selectData.value.brandList.find(i => i.bizId == v.bizId)?.brandName ||
          "--";
        brandGoodsPrice.push(v);
      } else {
        // 门店
        let obj = selectData.value.storeList.find(i => i.id == v.bizId);
        if (obj) {
          v.brandId = obj.brandId;
          v.brandName = obj.storeName;
        }
        storeGoodsPrice.push(v);
      }
    });

    return brandGoodsPrice.map(v => {
      // 处理门店
      v.storeList = storeGoodsPrice.filter(i => i.brandId == v.bizId);
      return v;
    });
  };

  //  关联品牌
  const setBrandPriceRef = ref();
  const changeBrandPrice = row => {
    let oriGoodsSpenData = JSON.parse(JSON.stringify(row));
    addDialog({
      title: "关联品牌",
      props: {
        brandPriceList:
          dealBrandList(oriGoodsSpenData.goodsSpecBrandRelList) || []
      },
      width: "1000px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(SetBrandPrice, { ref: setBrandPriceRef }),
      beforeSure: done => {
        let saveBrandPriceData = setBrandPriceRef.value.getSaveBrandPriceList();
        if (saveBrandPriceData.isCanNext) {
          let specBrandRelList = saveBrandPriceData.goodsSpecBrandRelList;
          let params = {
            specId: row.id,
            specBrandRelList
          };
          setGoodsSpen(params);
          message("操作成功", { type: "success" });
          row.goodsSpecBrandRelList = specBrandRelList;
          onSearch();
          done();
        }
      },
      beforeCancel: done => {
        done();
      }
    });
  };

  function onChangeStatus({ row }) {
    let goodsStatus = 1;
    if (row.goodsStatus == 1) {
      goodsStatus = 0;
    }
    //商品状态 0停用 1启用
    let optStr = row.goodsStatus == 1 ? "停用" : "启用";
    ElMessageBox.confirm(
      `确认要<strong>${optStr}</strong><strong style='color:var(--el-color-primary)'>'${
        row.goodsName
      }'</strong>商品吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        await batchUpGoodsStatus({ goodsIds: [row.id], goodsStatus });
        row.goodsStatus = goodsStatus;
        message(optStr + "成功", {
          type: "success"
        });
      })
      .catch(() => {});
    return false;
  }

  function onChangeRecommend({ row }) {
    let recommendStatus = 1;
    if (row.recommendStatus == 1) {
      recommendStatus = 0;
    }
    // 推荐状态 0不推荐 1推荐
    let optStr = row.recommendStatus == 1 ? "不推荐" : "推荐";
    ElMessageBox.confirm(
      `确认要<strong>${optStr}</strong><strong style='color:var(--el-color-primary)'>'${
        row.goodsName
      }'</strong>商品吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        await batchRecommendGoods({ goodsIds: [row.id], recommendStatus });
        row.recommendStatus = recommendStatus;
        message("操作成功", {
          type: "success"
        });
      })
      .catch(() => {});
    return false;
  }

  // 删除规格
  const handleDeleteSpec = async row => {
    await delGoodsSpec(row.id);
    message("删除成功", { type: "success" });
    onSearch();
  };

  // 删除商品
  const handleDelete = async row => {
    await delGoods(row.id);
    message("删除成功", { type: "success" });
    onSearch();
  };

  function handleSizeChange(val: number) {
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.pageNum = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量操作 */
  function onBatchStart(goodsStatus) {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const optIds = getKeyList(curSelected, "id");
    console.log("curSelected");
    if (optIds.length <= 0) {
      message("请选择要操作的数据", {
        type: "warning"
      });
    }

    ElMessageBox.confirm(
      `确认要<strong>${goodsStatus == 1 ? "批量启用" : "批量停用"}</strong>选中的商品吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        await batchUpGoodsStatus({ goodsIds: optIds, goodsStatus });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
        message("操作成功", {
          type: "success"
        });
      })
      .catch(() => {});
  }

  async function onSearch() {
    loading.value = true;
    let tempForm = { ...form };
    if (tempForm.categoryId === 0) {
      delete tempForm.categoryId;
    }
    if (tempForm.labelIdList && tempForm.labelIdList.length > 0) {
      tempForm.labelIds = tempForm.labelIdList.join(",");
    }
    delete tempForm.labelIdList;
    const { data } = await getGoodsList(tempForm);
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.categoryId = null;
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect(treeData) {
    let { id, selected, menuName } = treeData;
    form.categoryId = selected ? id : null;
    currentTreeData.id = selected ? id : null;
    currentTreeData.menuName = selected ? menuName : null;
    onSearch();
  }

  function openDialog(title = "新增", row?: any) {
    addDialog({
      sureBtnLoading: true,
      title: title + "商品",
      props: {
        formInline: {
          id: row?.id ?? undefined,
          title,
          menuName: row?.menuName ?? "",
          menuIcon: row?.menuIcon ?? "",
          menuUri: row?.menuUri ?? "",
          menuCode: row?.menuCode ?? "",
          preStockStatus: row?.preStockStatus ?? 1,
          selectData: selectData.value
        },
        selectData: selectData.value || {}
      },
      width: "1200px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: async (done, { options, closeLoading }) => {
        let isCanNext = await formRef.value.isCanNext();
        console.log("isCanNext", isCanNext);
        if (!isCanNext) {
          console.log("校验不通过");
          closeLoading();
          return;
        }

        function chores() {
          message("操作成功", {
            type: "success"
          });
          onSearch(); // 刷新表格数据
          done(); // 关闭弹框
        }

        // 处理数据
        const curData = options.props.formInline;
        console.log("curData", curData);
        let reqData = { ...curData };
        delete reqData.title;
        delete reqData.selectData;
        delete reqData.delSpecIds;
        delete reqData.inputBraCodeList;
        reqData.recommendIndex = dealDataRide(reqData.recommendIndex, 10) || 0;
        reqData.goodsExchangeFareRuleList =
          reqData.goodsExchangeFareRuleList.map(v => {
            return {
              province: v.province,
              fareScore: dealDataRide(v.fareScore),
              farePrice: dealDataRide(v.farePrice)
            };
          }) || [];
        if (reqData.goodsType == 1) {
          reqData.goodsExchangeFareRuleList = [];
        }

        console.log("reqData", reqData);
        console.log("curData", curData.delSpecIds);
        // if (true) {
        //   closeLoading();
        //   return;
        // }

        // 表单规则校验通过
        if (title === "新增") {
          // 实际开发先调用新增接口，再进行下面操作
          addGoods(reqData)
            .then(() => chores())
            .catch(() => closeLoading());
        } else {
          // 实际开发先调用修改接口，再进行下面操作

          upGoods(reqData)
            .then(async () => {
              // 保存成功后，删除规格
              if (curData.delSpecIds && curData.delSpecIds.length > 0) {
                curData.delSpecIds.forEach(async v => await delGoodsSpec(v));
              }
              chores();
            })
            .catch(() => closeLoading());
          closeLoading();
        }
      }
    });
  }

  /** 加载菜单tree */
  const loadTree = async () => {
    treeLoading.value = true;
    // 获取菜单
    let params = {
      pageNum: 1,
      pageSize: 500
    };
    // 商品类目
    let cateData = await getCategoryPgae(params);
    selectData.value.categoryList = handleTree(cateData.data.records || []);
    treeData.value = [
      {
        value: 0,
        id: 0,
        label: "全部",
        categoryName: "全部",
        children: selectData.value.categoryList
      }
    ];
    treeLoading.value = false;
    // 默认选择第一个
    // nextTick(() => {
    //   let tempData = treeData.value[0];
    //   if (tempData.children && tempData.children.length > 0) {
    //     let childData = tempData.children[0];
    //     form.categoryId = childData.id;
    //     currentTreeData.id = childData.id;
    //     currentTreeData.menuName = childData.menuName;
    //     treeRef && treeRef.value.setCurrentKey(childData.id);
    //   }
    // });
  };

  const initData = async () => {
    loadTree();
    onSearch();

    let params = {
      pageNum: 1,
      pageSize: 500
    };

    // 门店
    getStoreSimplePage({ status: 0, ...params }).then(res => {
      selectData.value.storeList = res.data?.records || [];
    });

    // 供应商
    getSupplierPage({ status: 0, ...params }).then(res => {
      selectData.value.supplierList = res.data?.records || [];
    });

    // 标签
    getLabelPage({ categoryId: 43, ...params }).then(res => {
      selectData.value.labelList = dealTreeList(
        res.data?.records || [],
        "categoryId",
        "categoryName",
        "labelName"
      );
    });

    // 计量单位
    getUnitItemList(params).then(res => {
      selectData.value.unitItemlList = dealTreeList(
        res.data?.records || [],
        "unitId",
        "unitName",
        "itemName"
      );
    });

    // 兑换规则
    getRuleList(params).then(res => {
      selectData.value.ruleList = res.data?.records || [];
    });

    // 品牌
    getBrandPage(params).then(res => {
      let tempList = res.data?.records || [];
      selectData.value.brandList = tempList.map(v => {
        return {
          id: v.id,
          bizId: v.id,
          bizType: 1,
          brandName: v.brandName,
          goodsStatus: 0,
          discountSalePrice: "",
          discountScore: "",
          score: "",
          storeBuyPrice: "",
          storeSalePrice: "",
          storeList: []
        };
      });
    });
  };

  // 下载模版
  const downTemp = () => {
    window.open("/template/商品导入模板.xls", "_blank");
  };

  // 导入数据
  const handleUpload = option => {
    return new Promise(resolve => {
      const formData = new FormData();
      formData.append("file", option.file);
      importGoodsList(formData)
        .then(() => {
          message("导入成功", { type: "success" });
          onSearch();
        })
        .catch(e => {
          let tips = e || "导入异常";
          if (e && e.split(";").length > 0) {
            tips = e.split(";").join("<br />");
          }
          ElMessageBox.alert(tips, "温馨提示", {
            dangerouslyUseHTMLString: true,
            showClose: true,
            confirmButtonText: "确认"
          });
        })
        .finally(() => {
          uploadRef.value.clearFiles();
        });
      resolve(true);
    });
  };

  const beforeUpload = file => {
    const last = file.name.substring(file.name.lastIndexOf(".") + 1);
    const extension1 = last == "xls";
    const extension2 = last == "xlsx";
    const isLtM = file.size / 1024 / 1024 < 20;
    if (!extension1 && !extension2) {
      message("上传文件格式只能是xls、xlsx格式!", { type: "warning" });
      return false;
    }
    if (!isLtM) {
      message("文件大小不能超过 20MB!", { type: "warning" });
      return false;
    }
  };

  onMounted(() => {
    if (treeRef) {
      initData();
    }
  });

  watch(tabType, () => {
    if (!treeRef) {
      return;
    }
    form.categoryId = null;
    form.pageNum = 1;
    form.pageSize = 20;
    currentTreeData.id = null;
    currentTreeData.menuName = "";
    treeRef.value.onTreeReset();
    initData();
  });

  return {
    form,
    loading,
    columns,
    childColumns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    currentTreeData,
    tabType,
    selectData,
    deviceDetection,
    onSearch,
    loadTree,
    resetForm,
    onBatchStart,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    handleDeleteSpec,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    showOptLog,
    changeBrandPrice,
    downTemp,
    handleUpload,
    beforeUpload
  };
}
